package com.fangmou.ing.publish.freemarker.directive;

import java.io.IOException;
import java.util.Map;

import com.fangmou.ing.publish.freemarker.DirectiveUtils;
import com.fangmou.ing.publish.freemarker.DirectiveBodyWraper;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * block重写命令
 * @必传参数：name（对应父模板中block名称）
 * @author badqiu
 */
public class OverrideDirective implements TemplateDirectiveModel {

  public void execute(Environment env, Map params, TemplateModel[] loopVars,
      TemplateDirectiveBody body) throws TemplateException, IOException {
    String name = DirectiveUtils.getRequiredParam(params, "name");
    String overrideVariableName = DirectiveUtils.getOverrideVariableName(name);

    DirectiveBodyWraper override = DirectiveUtils.getOverrideBody(env, name);
    DirectiveBodyWraper current = new DirectiveBodyWraper(body, env);

    if (override == null) {
      env.setVariable(overrideVariableName, current);
    } else {
      DirectiveUtils.setTopBodyForParentBody(env, current, override);
    }
  }
}
